package com.sugon.controller.spare;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.AutoLog;
import com.sugon.annotation.NonBusinessParamValid;
import com.sugon.entity.SparePartSafeStockEntity;
import com.sugon.entity.vo.SparePartSafeStockNewlyAddParam;
import com.sugon.modules.base.model.vo.BaseApproveParamVO;
import com.sugon.modules.sparepart.consts.SparePartSafeStockState;
import com.sugon.modules.sparepart.service.ISparePartSafeStockManager;
import com.sugon.service.SparePartSafeStockService;
import com.sugon.service.SysConfigService;
import com.sugon.utils.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 各车间备件安全库存配置Controller
 *
 * @author sugon
 * @date 2022-07-04 10:03:38
 */
@Controller
@RequestMapping("sparepartsafestock")
public class SparePartSafeStockController {

    @Resource
    private SparePartSafeStockService sparePartSafeStockService;
    @Resource
    private SysConfigService configService;
    @Resource
    private ISparePartSafeStockManager sparePartSafeStockManager;

    /**
     * 查看列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("sparepartsafestock:list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<SparePartSafeStockEntity> sparePartSafeStockList = sparePartSafeStockService.queryList(query);
        int total = sparePartSafeStockService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(sparePartSafeStockList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }

    /**
     * 查看信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("sparepartsafestock:info")
    @ResponseBody
    public R info(@PathVariable("id") String id) {
        SparePartSafeStockEntity sparePartSafeStock = sparePartSafeStockService.queryObject(id);
        return R.ok().put("sparePartSafeStock", sparePartSafeStock);
    }

    /**
     * 保存
     */
    @NonBusinessParamValid
    @RequestMapping("/save")
    @RequiresPermissions("sparepartsafestock:save")
    @ResponseBody
    public R save(@Validated @RequestBody SparePartSafeStockNewlyAddParam newlyAddParam, BindingResult bindingResult) {
        // 非车间人员不得添加安全库存
        String workshop = ShiroUtils.getWorkshop();
        if (StrUtil.isEmpty(workshop)) {
            return R.error("非车间用户，不允许添加！");
        }
        // 校验当前车间是否已为这个备件建立安全库存
        List<SparePartSafeStockEntity> existedList = sparePartSafeStockService.queryList(workshop, newlyAddParam.getSparePartId());
        if (CollectionUtil.isNotEmpty(existedList)) {
            return R.error("当前备件安全库存已设置，请勿重新操作！");
        }
        return sparePartSafeStockService.configDeptSafeStock(newlyAddParam) ? R.ok() : R.error("添加失败，请稍后重试！");
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sparepartsafestock:update")
    @ResponseBody
    public R update(@RequestBody SparePartSafeStockEntity sparePartSafeStock) {
        sparePartSafeStockService.update(sparePartSafeStock);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sparepartsafestock:delete")
    @ResponseBody
    public R delete(@RequestBody String[] ids) {
        sparePartSafeStockService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 查看所有列表
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public R queryAll(@RequestParam Map<String, Object> params) {

        List<SparePartSafeStockEntity> list = sparePartSafeStockService.queryList(params);

        return R.ok().put("list", list);
    }

    @RequiresPermissions("sparepartsafestock:export")
    @RequestMapping("/export")
    @ResponseBody
    public void export(@RequestParam Map<String, Object> params, ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException {
        // 移除空值，防止出现
        MapUtil.removeEmptyValue(params);
        List<SparePartSafeStockEntity> sparePartList = sparePartSafeStockService.queryList(params);
        Map<String, Object> map = new HashMap<>(1);
        map.put("list", sparePartList);
        // 构建模板导出参数
        TemplateExportParams templateExportParams = new TemplateExportParams(configService.getPoiTemplatePath() + "sparePartSafeStockIETemplate.xlsx");
        templateExportParams.setColForEach(true);
        modelMap.put(TemplateExcelConstants.FILE_NAME, "安全库存列表_" + com.sugon.modules.utils.DateUtil.today());
        modelMap.put(TemplateExcelConstants.PARAMS, templateExportParams);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response, TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);
    }

    @RequiresPermissions("sparepartsafestock:import")
    @RequestMapping("/import")
    @ResponseBody
    public R importE(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }
        int count = sparePartSafeStockService.importE(file);
        return R.ok("成功导入" + count + "条数据");
    }

    @RequestMapping("/commitApprove")
    @RequiresPermissions("sparepartsafestock:commitApprove")
    @ResponseBody
    public R commitApprove(@RequestParam String safeStockId) {
        // 校验是否存在
        SparePartSafeStockEntity safeStock = sparePartSafeStockService.queryObject(safeStockId);
        if (safeStock == null) {
            return R.error("备件安全库存设置不存在，请确认!");
        }
        // 校验是否审核中
        String state = safeStock.getState();
        if (StrUtil.equalsAny(state, SparePartSafeStockState.DEPT_APPROVING, SparePartSafeStockState.PASSED)) {
            return R.error("备件安全库存设置审核中或已通过审核，无需重复提交!");
        }
        // 只可以提交自己编制的需求计划
        if (!safeStock.getCreateUser().equals(ShiroUtils.getUserId())) {
            return R.error("只可以提交自己设置的备件安全库存！");
        }
        return sparePartSafeStockManager.commitApprove(safeStock) ? R.ok() : R.error("提交失败，请稍后重试!");
    }

    /**
     * 车间授权人审批
     */
    @NonBusinessParamValid
    @RequestMapping("/check")
    @RequiresPermissions("sparepartsafestock:check")
    @ResponseBody
    public R check(@Validated @RequestBody BaseApproveParamVO approveParam, BindingResult bindingResult) {
        approveParam.setProcessItem(ProcessInfoEnum.SPA_BJAQKC);
        return sparePartSafeStockManager.workshopApprove(approveParam) ? R.ok() : R.error();
    }

}
